<?php
namespace app\admin\service;
class ImageService
{
    /**
     * 压缩图片覆盖原图
     * @param $imagePath
     * @param int $maxMB
     * @return bool|string
     */
    public function compressImage($imagePath,$maxMB =0.7) {
        try{
            if(!file_exists($imagePath)){
                return false;
            }
            // 获取图片信息
            list($width, $height, $type) = getimagesize($imagePath);

            // 计算图片文件大小
            $filesize = filesize($imagePath);
            $filesizeMB = $filesize / (1024 * 1024); // 将文件大小转换为MB

            // 如果图片大小超过1MB，则进行压缩
            if ($filesizeMB > $maxMB) {



                $imageRate = round($width/$height,2);


                switch ($type) {
                    case IMAGETYPE_JPEG:
                        $source = imagecreatefromjpeg($imagePath);
                        $compressedImage = date("YmdHis").uniqid().".jpg";
                        break;
                    case IMAGETYPE_PNG:
                        $source = imagecreatefrompng($imagePath);
                        $compressedImage = date("YmdHis").uniqid().".png";

                        // 新的画布保留透明通道
                       /* imagealphablending($newImage, false);
                        $transparent = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
                        imagefill($newImage, 0, 0, $transparent);
                        imagesavealpha($newImage, true);*/
                        break;
                    case IMAGETYPE_GIF:
                        $compressedImage = date("YmdHis").uniqid().".gif";
                        $source = imagecreatefromgif($imagePath);
                        break;
                    default:
                        return $imagePath; // 不支持的图片类型
                }

                $exif = exif_read_data($imagePath);
                if (!empty($exif['Orientation'])) {
                    $orientation = $exif['Orientation'];
                    switch ($orientation) {
                        case 8:
                            $source = imagerotate($source, 90, 0);
                            $tempWidth = $width;
                            $width = $height;
                            $height = $tempWidth;
                            break;
                        case 3:
                            $source = imagerotate($source, 180, 0);
                            break;
                        case 6:
                            $tempWidth = $width;
                            $width = $height;
                            $height = $tempWidth;
                            $source = imagerotate($source, 270, 0);
                            break;
                    }
                }

                $compressionRatio = sqrt( 0.7/$filesizeMB); // 压缩至0.7M以下
                $newWidth = round($width * $compressionRatio,2);
                $newHeight = round($height * $compressionRatio,2);
                $newImage = imagecreatetruecolor($newWidth, $newHeight);


                    // 执行压缩
                imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                // 保存压缩后的图片
                $compressedImagePath = dirname($imagePath)."/".$compressedImage;
                $compressedImagePath = $imagePath;//覆盖原图
                $quality = 70;
                switch ($type) {
                    case IMAGETYPE_JPEG:
                        imagejpeg($newImage, $compressedImagePath, $quality);
                        break;
                    case IMAGETYPE_PNG:
                        imagepng($newImage, $compressedImagePath);
                        break;
                    case IMAGETYPE_GIF:
                        imagegif($newImage, $compressedImagePath);
                        break;
                    default:
                        return false; // 不支持的图片类型
                }
                imagedestroy($newImage);
                imagedestroy($source);
                return $compressedImagePath;
            } else {
                return $imagePath; // 图片大小未超过1MB，不需要压缩
            }
        }catch (\Exception $e){
            $error = "行".$e->getLine();
            $error .= "消息".$e->getMessage();
            trace_log($error,'compressImage_except');
            return false;
        }
    }
}
